package bingosoft.metro.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import bingosoft.components.base.helper.ObjectHelper;
import bingosoft.components.base.service.BaseService;
import bingosoft.components.base.service.PageQueryRequest;
import bingosoft.components.base.service.Result;
import bingosoft.components.base.service.ResultEntity;
import bingosoft.components.base.service.ResultPage;
import bingosoft.metro.demo.form.DemoUserForm;
import bingosoft.metro.demo.iservice.IDemoUserService;
import bingosoft.metro.demo.model.DemoUserModel;
import bingosoft.metro.variable.VariableFactory;
import leap.core.exception.RecordNotDeletedException;
import leap.core.exception.RecordNotFoundException;
import leap.core.exception.RecordNotSavedException;
import leap.lang.Strings;
import leap.orm.query.PageResult;
import leap.orm.query.Query;

/**
 * @author feily
 * @功能描述 用户业务服务接口实现类
 * @创建时间 2018-02-28 13:53:46
 */
public class DemoUserService extends BaseService implements IDemoUserService {

	public static final String MESSAGE_PARAM_OBJ_NULL = "参数【demoUserModel】不能为null！";
	public static final String MESSAGE_PARAM_ID_NULL = "参数【userId】不能为空！";
	public static final String MESSAGE_QUERY_FAIL = "查询失败！";
	public static final String MESSAGE_CREATE_SUCCESS = "创建成功！";
	public static final String MESSAGE_CREATE_FAIL = "创建失败（没有数据被创建）！";
	public static final String MESSAGE_UPDATE_SUCCESS = "修改成功！";
	public static final String MESSAGE_UPDATE_FAIL = "修改失败（ID不存在或没有数据被修改）！";
	public static final String MESSAGE_GET_SUCCESS = "获取成功！";
	public static final String MESSAGE_GET_FAIL = "获取失败（ID不存在）！";
	public static final String MESSAGE_DELETE_SUCCESS = "删除成功！";
	public static final String MESSAGE_DELETE_FAIL = "删除失败（没有数据被删除）！";
	
	/**
	 * 构建函数
	 */
	public DemoUserService(){
		this.setLogClass(this.getClass());
	}
	
	@Override
	public ResultEntity<List<DemoUserForm>> queryDemoUsers(PageQueryRequest pageQueryRequest, Map<String, Object> params) {
		this.logMethodCalled("queryDemoUsers");
		this.logParamValue("pageQueryRequest", pageQueryRequest);
		this.logParamValue("params", params);
		
		if(pageQueryRequest == null){
			pageQueryRequest = new PageQueryRequest();
		}
		
		// 构建查询SQL
		String selectSql = this.buildSelectSql("");
		pageQueryRequest.mergeFilters(selectSql, params);

		// 构建查询对象
		Query<DemoUserModel> query = DemoUserModel.<DemoUserModel>query(pageQueryRequest.getMergeSql()).params(pageQueryRequest.getParameter());
		if(!Strings.isEmpty(pageQueryRequest.getSort())){
			query = query.orderBy(pageQueryRequest.getSort());
		}

		// 返回查询结果
		ResultEntity<List<DemoUserForm>> resultEntity = new ResultEntity<List<DemoUserForm>>();
		try {
			List<DemoUserModel> demoUserModels = query.list();
			// 构建表单类
			List<DemoUserForm> demoUserForms = this.buildDemoUserForms(demoUserModels);
			
			resultEntity.setBusinessObject(demoUserForms);
		} catch (Exception ex) {
			this.logError(MESSAGE_QUERY_FAIL, ex);
			resultEntity.setSuccess(false);
			resultEntity.setMessage(Strings.format("{0}[{1}]", MESSAGE_QUERY_FAIL,ex.getMessage()));
		}
		return resultEntity;
	}

	@Override
	public ResultEntity<ResultPage<List<DemoUserForm>>> pageQueryDemoUsers(PageQueryRequest pageQueryRequest, Map<String, Object> params) {
		this.logMethodCalled("pageQueryDemoUsers");
		this.logParamValue("pageQueryRequest", pageQueryRequest);
		this.logParamValue("params", params);

		if(pageQueryRequest == null){
			pageQueryRequest = new PageQueryRequest();
		}
		
		int pageIndex = pageQueryRequest.getIndex();
		int pageSize = pageQueryRequest.getSize();
		this.logParamValue("pageIndex", pageIndex);
		this.logParamValue("pageSize", pageSize);
		
		// 构建查询SQL
		String selectSql = this.buildSelectSql("");
		pageQueryRequest.mergeFilters(selectSql, params);

		// 构建查询对象
		Query<DemoUserModel> query = DemoUserModel.<DemoUserModel>query(pageQueryRequest.getMergeSql()).params(pageQueryRequest.getParameter());
		if(!Strings.isEmpty(pageQueryRequest.getSort())){
			query = query.orderBy(pageQueryRequest.getSort());
		}
		
		// 返回查询结果
		ResultEntity<ResultPage<List<DemoUserForm>>> resultEntity = new ResultEntity<ResultPage<List<DemoUserForm>>>();
		try {
			PageResult<DemoUserModel> pageResult = query.pageResult(pageIndex, pageSize);
			List<DemoUserModel> demoUserModels = pageResult.list();
			
			// 构建表单类
			List<DemoUserForm> demoUserForms = this.buildDemoUserForms(demoUserModels);
			
			ResultPage<List<DemoUserForm>> resultPage = new ResultPage<List<DemoUserForm>>();
			resultPage.setRows(demoUserForms);
			resultPage.setPage(pageIndex);
			resultPage.setSize(pageSize);
			resultPage.setRecords(pageResult.getTotalCount());
			resultEntity.setBusinessObject(resultPage);
			
		} catch (Exception ex) {
			this.logError(MESSAGE_QUERY_FAIL, ex);
			resultEntity.setSuccess(false);
			resultEntity.setMessage(Strings.format("{0}[{1}]", MESSAGE_QUERY_FAIL,ex.getMessage()));
		}
		return resultEntity;
	}

	@Override
	public Result createDemoUser(DemoUserForm demoUserForm) {
		this.logMethodCalled("createDemoUser");
		this.logParamValue("demoUserForm", demoUserForm);
		
		Result result = new Result();	
		
		// 参数验证
		if(demoUserForm == null){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_OBJ_NULL);
			return result;
		}
		
		// 构建模型类
		if(Strings.isEmpty(demoUserForm.getUserId())){
			demoUserForm.setUserId(ObjectHelper.getUUID());
		}
		DemoUserModel demoUserModel = new DemoUserModel();
		demoUserForm.copyTo(demoUserModel);
		demoUserModel.setCreateTime(new Date());
		demoUserModel.setCreateUserId(VariableFactory.getUserId());
		
		try {
			demoUserModel.create();
			result.setMessage(MESSAGE_CREATE_SUCCESS);
		} catch (RecordNotSavedException e) {
			result.setSuccess(false);
			result.setMessage(MESSAGE_CREATE_FAIL);
		}
		return result;
	}

	@Override
	public Result updateDemoUser(DemoUserForm demoUserForm) {
		this.logMethodCalled("updateDemoUser");
		this.logParamValue("demoUserForm", demoUserForm);
		
		boolean isSuccess = true;
		Result result = new Result();	
		
		// 参数验证
		if(demoUserForm == null){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_OBJ_NULL);
			return result;
		}
		
		// 获取用户
		String userId = demoUserForm.getUserId();
		ResultEntity<DemoUserModel> resultEntity = this.getDemoUserModel(userId);
		if(!resultEntity.isSuccess()){
			result.setSuccess(false);
			result.setMessage(resultEntity.getMessage());
			result.setStatusCode(resultEntity.getStatusCode());
			return result;
		}
		
		// 设置值
		DemoUserModel demoUserModel = resultEntity.getBusinessObject();
		demoUserForm.copyTo(demoUserModel);
		demoUserModel.setUpdateTime(new Date());
		demoUserModel.setUpdateUserId(VariableFactory.getUserId());
		
		try {
			demoUserModel.update();
			result.setMessage(MESSAGE_UPDATE_SUCCESS);
		} catch (IllegalStateException e1) {
			isSuccess = false;
		} catch (RecordNotSavedException e2) {
			isSuccess = false;
		}

		if(!isSuccess){
			result.setSuccess(false);
			result.setMessage(MESSAGE_UPDATE_FAIL);
		}
		return result;
	}

	@Override
	public ResultEntity<DemoUserForm> getDemoUser(String userId) {
		this.logMethodCalled("getDemoUser");
		this.logParamValue("userId", userId);
		
		ResultEntity<DemoUserModel> resultEntity = this.getDemoUserModel(userId);
		
		ResultEntity<DemoUserForm> resultForm = new ResultEntity<DemoUserForm>();
		resultForm.setMessage(resultEntity.getMessage());
		resultForm.setStatusCode(resultEntity.getStatusCode());
		
		if(resultEntity.isSuccess()){
			DemoUserForm demoUserForm = new DemoUserForm();
			demoUserForm.copyFrom(resultEntity.getBusinessObject());
			resultForm.setBusinessObject(demoUserForm);
		}else{
			resultForm.setSuccess(false);
		}
		return resultForm;
	}
	
	@Override
	public ResultEntity<DemoUserModel> getDemoUserModel(String userId) {
		this.logMethodCalled("getDemoUser");
		this.logParamValue("userId", userId);
		
		ResultEntity<DemoUserModel> resultEntity = new ResultEntity<DemoUserModel>();
		
		// 参数验证
		if(Strings.isEmpty(userId)){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(MESSAGE_PARAM_ID_NULL);
			return resultEntity;
		}
		
		try {
			DemoUserModel demoUserModel = DemoUserModel.find(userId);
			resultEntity.setMessage(MESSAGE_GET_SUCCESS);
			resultEntity.setBusinessObject(demoUserModel);
		} catch (RecordNotFoundException e) {
			resultEntity.setSuccess(false);
			resultEntity.setMessage(MESSAGE_GET_FAIL);
		}
		return resultEntity;
	}

	@Override
	public Result deleteDemoUser(String userId) {
		this.logMethodCalled("deleteDemoUser");
		this.logParamValue("userId", userId);
			
		Result result = new Result();	
		
		// 参数验证
		if(Strings.isEmpty(userId)){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_ID_NULL);
			return result;
		}
		
		try {
			DemoUserModel.delete(userId);
			result.setMessage(MESSAGE_DELETE_SUCCESS);
		} catch (RecordNotDeletedException e) {
			result.setSuccess(false);
			result.setMessage(MESSAGE_DELETE_FAIL);
		}
		return result;
	}

	@Override
	protected String getTableName() {
		return DemoUserModel.metamodel().getTableName();
	}

	/**
	 * 构建表单类
	 * @param demoUserModels
	 * @return
	 */
	protected List<DemoUserForm> buildDemoUserForms(List<DemoUserModel> demoUserModels) {
		List<DemoUserForm> demoUserForms = new ArrayList<DemoUserForm>();
		for (DemoUserModel demoUserModel : demoUserModels) {
			DemoUserForm demoUserForm = new DemoUserForm();
			demoUserForm.copyFrom(demoUserModel);
			demoUserForms.add(demoUserForm);
		}
		return demoUserForms;
	}
}